package net.qqxh.resolve2view.impl;

import net.qqxh.resolve2view.File2ViewResolve;
import org.jodconverter.DocumentConverter;
import org.jodconverter.office.OfficeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @author yudian-it
 */
@Component
public class Word2ViewResolve implements File2ViewResolve {
    @Autowired
    private DocumentConverter documentConverter;
    private static String RESOLVE_LIST = ".doc|.docx";
    private static String RESOLVE2FIX = "pdf";

    /**
     * 转换office文档
     *
     * @param fromPath 源文件路径
     * @return toPath   view目标文件路径
     */
    @Override
    public String resolve(String fromPath,String toPath) throws OfficeException {
        File inputFile = new File(fromPath);
        File tofile = new File(toPath);
        if (inputFile.exists()) {// 找不到源文件, 则返回
            try {
                documentConverter.convert(inputFile).to(tofile).execute();
            } catch (OfficeException e) {
                e.printStackTrace();
                throw e;
            }
        }
        return toPath;
    }

    @Override
    public boolean canResolve(String fileFix) {
        return RESOLVE_LIST.contains(fileFix.toLowerCase());
    }

    @Override
    public String getviewFix() {
        return RESOLVE2FIX;
    }
}
